import logging

from aiogram import Bot
from fluentogram import TranslatorRunner

from src.application.bot_settings.service import BotSettingsService
from src.application.order.enums import OrderType
from src.application.order.service import OrderService
from src.application.user.service import UserService
from src.presentation.tg_bot.services.locale import Localizator
from src.presentation.tg_bot.services.tg_helpers import broadcast
from src.presentation.tg_bot.worker.exception_handler import exception_handler

logger = logging.getLogger(__name__)


@exception_handler
async def archiving_expired_orders(ctx) -> None:
    bot: Bot = ctx["bot"]
    fluent: Localizator = ctx["fluent"]
    bot_settings_service: BotSettingsService = ctx["bot_settings_service"]
    order_sevice: OrderService = ctx["order_service"]
    user_service: UserService = ctx["user_service"]

    bot_settings = await bot_settings_service.get_bot_settings()
    if bot_settings and bot_settings.order_archiving_status:
        success_count = 0
        orders = await order_sevice.get_expired_orders()
        for order in orders:
            logger.info(f"Архивирую заказ/подписку №{order.id}")

            user = await user_service.get_user_by_id(order.buyer_id)
            locale: TranslatorRunner = fluent.get_by_locale(user.lang_code.value)

            await order_sevice.archive_order(order.id)

            if order.order_type == OrderType.subscription:
                text = locale.get("subscription-expired")
            elif order.order_type == OrderType.vpn:
                text = locale.get("vpn-expired")
            else:
                text = locale.get("order-expired", order_id=str(order.id))

            logger.info(f"Архивировал заказ/подписку/впн №{order.id}")
            await broadcast(bot, [user.tg_id], text)
            success_count += 1

        if len(orders) > 0:
            logger.info(f"Архивировал успешно {success_count} из {len(orders)} заказ(ов)/подписок/впн")
